
export default class Slide {
    constructor(containerId, value, callback, ...args) {

        this.value = value;

        const container = document.querySelector(`#${containerId}`);
        const bar = container.children[0];
        const slider = bar.children[0];

        slider.style.left = container.offsetWidth * this.value + 'px';
        bar.style.width = container.offsetWidth * this.value + 'px';

        // 拖动滑块的事件
        slider.onmousedown = function (e) {

            // 每次滑动重新计算最大值，避免因窗口大小变化产生越界错误
            const max = container.offsetWidth - slider.offsetWidth;

            let barWidth = slider.offsetLeft;
            const event = e || window.event; //兼容性
            let mouseX = event.clientX; //鼠标按下的位置
            window.onmousemove = function (e) {
                const event = e || window.event;
                let moveL = event.clientX - mouseX; //鼠标移动的距离
                let newL = barWidth + moveL; //left值
                // 判断最大值和最小值
                if (newL < 0) {
                    newL = 0;
                }
                if (newL >= max) {
                    newL = max;
                }
                // 改变left值
                slider.style.left = newL + 'px';
                bar.style.width = newL + 'px';

                this.value = (newL / max).toFixed(2);

                return false; //取消默认事件
            }
            window.onmouseup = function () {
                // 鼠标弹起时写入数据
                callback(this, ...args);
                window.onmousemove = false; //解绑移动事件
                return false;
            }
            return false;
        };
    }
}

/*
<div class="bright-ctrl">
    <i class="fas fa-sun"></i>
    <div class="brightness">
        <div class="total" id="brightCtrl">
            <div class="bar">
                <div class="slider"></div>
            </div>
        </div>
    </div>
</div>
*/